package com.app.kit.tree;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qiangt
 */
public class TreeUtil {
    /**
     * 虚拟根节点ID
     */
    public static final String VIRTUAL_ROOT_ID = "-1";

    public static List<TreeNode> build(List<TreeNode> treeNodeList) {
        List<TreeNode> parentList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(treeNodeList)) {
            parentList = treeNodeList.stream().filter(o -> StrUtil.isBlank(o.getParentId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(parentList)) {
                parentList.sort(Comparator.comparing(TreeNode::getOrderNum));

                Map<String, List<TreeNode>> childrenMap = treeNodeList.stream().filter(o -> StrUtil.isNotBlank(o.getParentId())).collect(Collectors.groupingBy(TreeNode::getParentId));
                build(childrenMap, parentList);
            }
        }
        return parentList;
    }

    private static void build(Map<String, List<TreeNode>> childrenMap, List<TreeNode> parentList) {
        if (childrenMap != null && childrenMap.size() > 0 && CollectionUtils.isNotEmpty(parentList)) {
            for (TreeNode treeNode : parentList) {
                treeNode.setChildren(childrenMap.getOrDefault(treeNode.getId(), new ArrayList<>()));
                treeNode.getChildren().sort(Comparator.comparing(TreeNode::getOrderNum));
                childrenMap.remove(treeNode.getId());
                if (CollectionUtils.isNotEmpty(treeNode.getChildren())) {
                    build(childrenMap, treeNode.getChildren());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(parentList)) {
            for (TreeNode treeNode : parentList) {
                if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                    treeNode.setChildren(null);
                }
            }
        }
    }
}
